# app.py
import dash
from dash import dcc, html
from dash.dependencies import Input, Output
import plotly.graph_objs as go

# 初始化 Dash 应用
app = dash.Dash(__name__)
app.title = '坐标输入与折线图展示'

# 定义应用布局
app.layout = html.Div(children=[
    html.H1(children='输入坐标并生成折线图'),

    html.Div([
        html.Label('X 坐标 (逗号分隔):'),
        dcc.Input(
            id='x-input',
            type='text',
            placeholder='例如: 1,2,3,4,5',
            style={'width': '100%', 'padding': '10px'}
        ),
    ], style={'margin-bottom': '20px'}),

    html.Div([
        html.Label('Y 坐标 (逗号分隔):'),
        dcc.Input(
            id='y-input',
            type='text',
            placeholder='例如: 10,20,30,40,50',
            style={'width': '100%', 'padding': '10px'}
        ),
    ], style={'margin-bottom': '20px'}),

    html.Button('生成折线图', id='submit-button', n_clicks=0, style={'padding': '10px 20px'}),

    html.Div(id='error-message', style={'color': 'red', 'margin-bottom': '20px'}),

    dcc.Graph(id='line-chart')
])


# 回调函数，用于处理输入并生成图表
@app.callback(
    [Output('line-chart', 'figure'),
     Output('error-message', 'children')],
    [Input('submit-button', 'n_clicks')],
    [dash.dependencies.State('x-input', 'value'),
     dash.dependencies.State('y-input', 'value')]
)
def update_graph(n_clicks, x_str, y_str):
    if n_clicks == 0:
        return {}, ''

    if not x_str or not y_str:
        return {}, '请确保 X 和 Y 坐标都已输入。'

    try:
        x = list(map(float, x_str.split(',')))
        y = list(map(float, y_str.split(',')))

        if len(x) != len(y):
            return {}, 'X 和 Y 坐标的数量必须相同。'

        # 创建折线图
        figure = {
            'data': [
                go.Scatter(
                    x=x,
                    y=y,
                    mode='lines+markers',
                    marker=dict(color='blue'),
                    name='坐标点'
                )
            ],
            'layout': go.Layout(
                title='输入坐标的折线图',
                xaxis=dict(title='X 轴'),
                yaxis=dict(title='Y 轴')
            )
        }
        return figure, ''

    except ValueError:
        return {}, '请输入有效的数字。'


# 运行应用
if __name__ == '__main__':
    app.run_server(debug=True)